/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/**
 * 巴枪注册页面
 *  */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Button, Popover, Row, Col, Popconfirm, Table, Modal, Select, Spin } from 'antd';
import question from '@/assets/question.svg';
import { getLStorage } from '@/utils/utils';
import styles from '../style.less';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ allocation, loading, user }) => ({
  allocation,
  userInfo: user.currentUser.user_info,
  getListLoading: loading.effects['allocation/getDeviceNumberList'],
  postLoading: loading.effects['allocation/saveDeviceNumber'],
  selectLoading: loading.effects['allocation/getRegisterCodeInfoList'],
}))
@Form.create()
export default class GunRegister extends PureComponent {
  constructor(props) {
    super(props);
    const { phone, gp_area_ids = [], area_ids } = this.props.userInfo || {};

    const isCompany = area_ids == '*';
    const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
    const area_id = gp_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : gp_area_ids[0];
    this.state = {
      area_id,
    };
    this.columns = [
      {
        title: '工号',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
      },
      {
        title: '姓名',
        dataIndex: 'user_name',
        key: 'user_name',
        align: 'center',
      },
      {
        title: '设备码',
        dataIndex: 'device_number',
        key: 'device_number',
        align: 'center',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        render: (text, record) => {
          switch (text) {
            case '3':
              return '未审核通过';
            case '2':
              return '审核通过';
            case '1':
              return (
                <div className={styles.status}>
                  <span>等待审核中</span>
                  <Popover
                    overlayStyle={{ width: 250 }}
                    trigger="hover"
                    content={`请到“中天系统-产品导航-资产-设备管理-快宝新增数据审核”中进行审核。设备SN码：${
                      record.device_number
                    }。审核通过后即可使用。`}
                  >
                    <img alt="" src={question} />
                  </Popover>
                </div>
              );
            default:
              '';
          }
          return text;
        },
      },
      {
        title: '操作',
        align: 'center',
        render: (text, record) => (
          <Popconfirm
            placement="top"
            title="是否删除"
            onConfirm={this.onDelet.bind(this, record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];
  }

  componentDidMount() {
    this.getList();
  }

  onDelet(id) {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/deleteDeviceNumber',
      payload: {
        id,
      },
    }).then(() => {
      this.getList();
    });
  }

  onSubmit = e => {
    const {
      dispatch,
      form,
      setRecord: { type: brandType, branch_code, branch_name },
    } = this.props;
    const { area_id } = this.state;
    e.preventDefault();
    this.getFormValues(res => {
      const {
        code: { itemValues },
      } = res;
      const { courier_name, courier_phone, gun_account } = itemValues;
      dispatch({
        type: 'allocation/saveDeviceNumber',
        payload: {
          phone: courier_phone,
          user_name: courier_name,
          brand: brandType,
          branch_code,
          code: gun_account,
          branch_name,
          area_id,
        },
      }).then(val => {
        Modal.info({
          title: '温馨提示',
          okText: '知道了',
          maskClosable: true,
          onOk: () => {
            form.resetFields();
            this.getList();
          },
          content: <div>{val.msg}</div>,
        });
      });
    });
  };

  onSelected(value, option) {
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue({
      code: {
        key: value.key,
        label: value.label,
        itemValues: option.props.label,
      },
    });
  }

  getList = () => {
    const {
      dispatch,
      setRecord: { type: brandType, branch_code },
    } = this.props;
    const { area_id } = this.state;
    dispatch({
      type: 'allocation/getDeviceNumberList',
      payload: {
        brand: brandType,
        branch_code,
        area_id,
      },
    });
  };

  getFormValues = then => {
    const {
      form: { validateFields },
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;
      then(fieldsValue);
    });
  };

  handleSelectChange(visible) {
    const {
      dispatch,
      setRecord: { branch_code },
    } = this.props;
    const { area_id } = this.state;
    visible &&
      dispatch({
        type: 'allocation/getRegisterCodeInfoList',
        payload: {
          branch_code,
          area_id,
        },
      });
  }

  render() {
    const {
      showDetail,
      postLoading,
      getListLoading,
      selectLoading,
      form: { getFieldDecorator },
      allocation: { gunRegisterList, registerCodeInfoList },
      setRecord: { brand, branch_code },
    } = this.props;
    return (
      <div className={styles.gunRegister}>
        <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 24 }}>
          <Col span={18} className={styles.title}>
            <Form layout="inline" onSubmit={this.onSubmit}>
              <FormItem>
                {getFieldDecorator('code', {
                  rules: [
                    {
                      required: true,
                      message: '请先选择注册中通快递员',
                    },
                  ],
                })(
                  <Select
                    labelInValue
                    onSelect={this.onSelected.bind(this)}
                    style={{ width: 250 }}
                    placeholder="请选择注册中通快递员"
                    notFoundContent="暂无数据"
                    onDropdownVisibleChange={this.handleSelectChange.bind(this)}
                  >
                    {selectLoading && (
                      <Option key="spin" disabled>
                        <Spin size="small" />
                      </Option>
                    )}
                    {registerCodeInfoList.map((val, index) => {
                      const { gun_account, courier_name } = val;
                      return (
                        // eslint-disable-next-line react/no-array-index-key
                        <Option key={index} value={index} label={val}>
                          {`${gun_account}-${courier_name}`}
                        </Option>
                      );
                    })}
                  </Select>,
                )}
              </FormItem>
              <FormItem>
                <Button type="primary" htmlType="submit" loading={postLoading}>
                  发起注册
                </Button>
              </FormItem>
            </Form>
          </Col>
          <Col span={6}>
            <Row type="flex" align="middle" justify="end">
              <Col>
                <span>{brand}</span>
                <span>（{branch_code}）</span>
              </Col>
              <Col>
                <Button type="primary" onClick={() => showDetail(false)}>
                  返回
                </Button>
              </Col>
            </Row>
          </Col>
        </Row>
        <Table
          className={styles.Tables}
          dataSource={gunRegisterList}
          columns={this.columns}
          rowKey="id"
          pagination={false}
          loading={getListLoading}
        />
      </div>
    );
  }
}
